package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;

import com.ruoyi.common.enums.SystemFileRelationDataTypeEnums;
import com.ruoyi.common.exception.IcanException;
import com.ruoyi.common.exception.IcanResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.system.util.DataPathProperties;
import com.ruoyi.system.util.FilePathProperties;
import com.ruoyi.system.util.TiffFrameTool;
import com.ruoyi.system.util.TiffThumbnailUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommonService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //临时文件目录
    @Value("${ruoyi.temp}")
    private String temp;
    //存储的位置
    @Value("${ruoyi.profile}")
    private String  profile;

    @Value("${wdc.mbzbsjglFile}")
    private String  mbzbsjgl;



    public IcanResult subpackageUploadFile(MultipartFile file, String totalChunks, String chunkNumber, String identifier) throws IOException {
        Integer chunkNumberTemp = null;
        if (null != file) {

            if (StrUtil.isBlank(chunkNumber) && StrUtil.isBlank(totalChunks)) {
                chunkNumberTemp = 1;
            } else {
                chunkNumberTemp = Integer.valueOf(chunkNumber);
            }
            //临时目录
            File temporaryPath = new File(temp+ File.separator + identifier);

            File outFile = new File(temporaryPath, chunkNumberTemp + ".part");
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
                FileUtils.copyInputStreamToFile(inputStream, outFile);
            } finally {
                if (null != inputStream) inputStream.close();
            }
        }
        return IcanResult.success(identifier);
    }


    public IcanResult subpackageUploadMerge(String fileName, String identifier, Integer dataType, Integer fileType) {


        if (StrUtil.isBlank(fileName)){
            throw new IcanException("文件格式错误");
        }
        String[] split = fileName.split("\\.");
        if (split.length < 2) throw new IcanException("文件格式错误");

        //获得当前时间的 yyyy/mm/dd
        String s1 = DateUtils.returnYearAndMAndDay(DateUtil.date());
        //存储的路径
        String fileSavePath= profile+
                DataPathProperties.getFileSavePath(dataType) +FilePathProperties.getFileSavePath(fileType)
                +s1;
        File file1 = new File(fileSavePath);
        if (!file1.exists()) file1.mkdirs();
        //拿到所有的文件包
        File file = new File(temp+ File.separator  + identifier);
        if (!file.isDirectory() || file.listFiles().length == 0) return IcanResult.error("文件上传失败，请重新上传");

        File[] files = file.listFiles();
        //合并文件
        String lastFileName =com.ruoyi.common.utils.uuid.UUID.fastUUID() + fileName.substring(fileName.lastIndexOf("."));

//        if (dataType == SystemFileRelationDataTypeEnums.LSSJ.getCode()) {
//            lastFileName = fileName.substring(0, 2) + "_" + new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
//        }

        File lastFilePath = new File(fileSavePath + File.separator+lastFileName);

        FileOutputStream destTempfos = null;

        try {
            for (int i = 1; i <= files.length; i++) {
                File s = new File(temp+ File.separator   + identifier, i-1 + ".part");
                //在此处可能开始向存储目录开始输出
                destTempfos = new FileOutputStream(lastFilePath, true);
                FileUtils.copyFile(s, destTempfos);
            }
            destTempfos.flush();

            ArrayList<Object> objects = new ArrayList<>();


            try {
                //删除临时文件
                FileUtils.deleteDirectory(file);
                log.info("----------------------" + fileName + "---文件分包合并结束，生成文件见目录：" + lastFilePath.getPath()+"文件大小："+lastFilePath.length());
            }catch (Exception e) {
                e.printStackTrace();
            }
            //使用redis将其存储起来 然后等到 点击确定的时候 将其他的删除 保留最后一个

            //将文件存储至数据库
//            JsonMap jsonMap = saveBigFileToDB(dataType, fileType, fileName, lastFileName);
            //当前用户+wdc
            String s = redisTemplate.opsForValue().get(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc");

            //文件绝对路径
//            String xjjdlj = profile+File.separator+mbzbsjgl+File.separator+s1+File.separator+lastFileName;

            //文件相对路径
            String jdlj = DataPathProperties.getFileSavePath(dataType) +FilePathProperties.getFileSavePath(fileType)
                    +s1+File.separator+lastFileName;
             if (StrUtil.isBlank(s)){
                 //证明第一次
                 redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId()+":wdc",jdlj);
             }else {
                 s+=(";"+jdlj);
                 redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId()+":wdc",s);
             }
String tplj = "";
             if (lastFilePath.getName().endsWith(".tiff") || lastFilePath.getName().endsWith(".tif") || lastFilePath.getName().endsWith(".geotiff") ){
                    //得到文件名前缀
                 int i = lastFilePath.getName().lastIndexOf(".");
                 String subName = lastFilePath.getName().substring(0, i);

                 // TODO 设置地址
                 String tftp= profile+
                         DataPathProperties.getFileSavePath(dataType) +FilePathProperties.getFileSavePath(fileType)
                         +s1;

                        tftp= tftp+File.separator+subName+".jpg";
                 tplj= DataPathProperties.getFileSavePath(dataType) +FilePathProperties.getFileSavePath(fileType)
                                 +s1 +File.separator+subName+".jpg";


                 File output = new File(tftp);

                 TiffThumbnailUtil.generateThumbnail(lastFilePath,output,521,521);



             }

            Map<String, String> stringStringHashMap = new HashMap<>();
             //文件格式
            //查看是什么类型
            String gs  = FileTypeUtils.returnGs(jdlj);
            stringStringHashMap.put("wjgs",gs);
            stringStringHashMap.put("wjlg",jdlj);
            stringStringHashMap.put("tfjt",tplj);
            return IcanResult.success(stringStringHashMap);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件分包合并失败！！");
        } finally {
            try {
                if (null != destTempfos) destTempfos.close();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("文件分包合并失败！！");
            }
        }
        return IcanResult.success();
    }


    /**
     * 删除冗余文件
     * @param fileName
     */
    public void filedeletePath(String fileName,Integer dataType) {
        if (StrUtil.isBlank(fileName)){
            //清空redis
            redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc","");
        }else {

            //首先获取缓存中的数据
            String filePng = redisTemplate.opsForValue().get(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc");

            if (!StrUtil.isBlank(filePng)){
                List<String> collect = Arrays.asList(filePng.split(";")).stream().filter(s -> !fileName.equals(s)).collect(Collectors.toList());
                //将其过滤出来删除
                collect.forEach(item->{
                    String filePath = profile+ File.separator+item;
                    //进行删除
                    FileUtil.del(filePath);
                });
            }
            //清空redis
            redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc","");
        }


    }


    /**
     * 删除多个冗余文件
     * @param filePaths
     */
    public void filedeleteBathPath(String filePaths,Integer dataType) {

        if (StrUtil.isBlank(filePaths)){
            //清空redis
            redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc","");
        }else {
            //首先获取缓存中的数据
            String filePng = redisTemplate.opsForValue().get(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId());

            if (!StrUtil.isBlank(filePng)){
                List<String> strings = Arrays.asList(filePng.split(";"));

                List<String> saveString = Arrays.asList(filePaths.split(";"));

                List<String> collect = strings.stream()
                        .filter(s -> !saveString.contains(s)) // 核心过滤条件：元素不在list2中
                        .collect(Collectors.toList());

                //将其过滤出来删除
                collect.forEach(item->{
                    String filePath = profile+ File.separator+item;
                    //进行删除
                    FileUtil.del(filePath);
                });
            }
            //清空redis
            redisTemplate.opsForValue().set(DataPathProperties.getcd(dataType)+":"+SecurityUtils.getUserId() + ":wdc","");
        }


    }



}
